package cn.itcalvin.sncoal.cth.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;
import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "cn.itcalvin.sncoal.cth.mapper.main", sqlSessionTemplateRef = "mainSqlSessionTemplate")
public class MainDataSourceConfig {
    // 注入数据源配置
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.main")
    public DataSourceProperties mainDataSourceProperties() {
        return new DataSourceProperties();
    }

    // 创建数据库连接
    @Primary
    @Bean
    public DataSource mainDataSource() {
        return mainDataSourceProperties().initializeDataSourceBuilder().build();
    }

    // 创建session工厂
    @Primary
    @Bean
    public SqlSessionFactory mainSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapperxml/main/*.xml"));
        return sessionFactoryBean.getObject();
    }

    // 创建事务管理（按需添加）
    @Primary
    @Bean
    public DataSourceTransactionManager mainDataSourceTransactionManager() {
        return new DataSourceTransactionManager(mainDataSource());
    }

    // 会话管理
    @Primary
    @Bean
    public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
